package com.weixin.gong.utils.zip;

import com.google.common.io.Closeables;
import org.apache.commons.lang3.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * gzip抓取结果<br>
 * Created by ling.yang 2015/9/9 15:00.
 */
public class GZipUtil {

    public static final int BUFFER = 1024;

    public static byte[] gzip(String value) throws IOException {
        if (StringUtils.isBlank(value)) {
            return null;
        }
        GZIPOutputStream gzipOutputStream = null;
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(value.getBytes("utf-8"));
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);
            int count;
            byte data[] = new byte[BUFFER];
            while ((count = byteArrayInputStream.read(data, 0, BUFFER)) != -1) {
                gzipOutputStream.write(data, 0, count);
            }
            gzipOutputStream.finish();
            gzipOutputStream.flush();
            return byteArrayOutputStream.toByteArray();
        } finally {
            Closeables.close(byteArrayInputStream, false);
            Closeables.close(byteArrayOutputStream, false);
            Closeables.close(gzipOutputStream, false);
        }

    }

    public static String unGzip(byte[] bytes) throws IOException {
        if (bytes == null) {
            return null;
        }
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream);
        try {
            int count;
            byte data[] = new byte[BUFFER];
            while ((count = gzipInputStream.read(data, 0, BUFFER)) != -1) {
                byteArrayOutputStream.write(data, 0, count);
            }
            byteArrayOutputStream.flush();
            return new String(byteArrayOutputStream.toByteArray(), "utf-8");
        } finally {
            Closeables.close(byteArrayOutputStream, false);
            Closeables.close(byteArrayOutputStream, false);
            Closeables.close(gzipInputStream, false);
        }
    }
}
